//
//  RealmDemoController.m
//  realmDemo
//
//  Created by Aaron Peng on 16/8/25.
//  Copyright © 2016年 BUPT. All rights reserved.
//

#import "RealmDemoController.h"
#import "Masonry.h"
#import "Person.h"
#import "Dog.h"

static NSString *valueCellID = @"valueCellID";
static NSString *detailCellID = @"detailCellID";

@interface RealmDemoController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, weak) UITableView *personTableView;
@property (nonatomic, weak) UITableView *detailTableView;
@property (nonatomic, weak) UITextField *personQueryField;

@property (nonatomic, strong) NSMutableArray *person_infos;
@property (nonatomic, strong) NSMutableArray *dog_infos;
@property (nonatomic, strong) Person *person;

@end

@implementation RealmDemoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadRealmData];
    
    [self setupUI];
    
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:topView];
    
    UITableView *personTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    personTableView.backgroundColor = [UIColor whiteColor];
    self.personTableView = personTableView;
    personTableView.delegate = self;
    personTableView.dataSource = self;
    [self.view addSubview:personTableView];
    [self.personTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:valueCellID];
    
    UITableView *detailTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    detailTableView.backgroundColor = [UIColor whiteColor];
    self.detailTableView = detailTableView;
    detailTableView.delegate = self;
    detailTableView.dataSource = self;
    [self.view addSubview:detailTableView];
    [self.detailTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:detailCellID];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.right.left.equalTo(self.view).offset(0);
        make.height.offset(44);
    }];
    
    [personTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.left.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view);
        make.width.offset(self.view.bounds.size.width / 2);
    }];
    
    [detailTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(personTableView.mas_top);
        make.left.equalTo(personTableView.mas_right);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
    addButton.center = CGPointMake(350, 22);
//    NSLog(@"%@", NSStringFromCGPoint(topView.center));
    [addButton addTarget:self action:@selector(addPush) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:addButton];
    
    UITextField *personQueryField = [[UITextField alloc] init];
    personQueryField.borderStyle = UITextBorderStyleRoundedRect;
    personQueryField.placeholder = @"请输入人的姓名";
    personQueryField.delegate = self;
    self.personQueryField = personQueryField;
    [topView addSubview:personQueryField];
    [personQueryField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [personQueryField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.offset(4);
        make.right.offset(-52);
        make.bottom.offset(-4);
    }];
    
}

-(void)viewDidLayoutSubviews{
    [self.personTableView reloadData];
    [self.detailTableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated{
    [self loadRealmData];
    [self.personTableView reloadData];
    [self.detailTableView reloadData];
}

#pragma mark - load Realm Data

- (void)loadRealmData {
    RLMResults *results = [Person allObjects];
    
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < results.count; i++) {
        Person *person = results[i];
        [array addObject:person];
    }
    
    self.person_infos = array;
}

#pragma mark - tableView DataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.personTableView) {
        return self.person_infos.count;
    }
    else {
        if (self.dog_infos.count != 0) {
            return self.dog_infos.count;
        }
        else {
            return 1;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSLog(@"%@", tableView);
    
    if (tableView == self.personTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:valueCellID forIndexPath:indexPath];
        cell = [cell initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:valueCellID];
        
        Person *info = self.person_infos[indexPath.row];
        
        cell.textLabel.text = info.name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%zd岁", info.age];
        
        return cell;
    }
    
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailCellID forIndexPath:indexPath];
        
        if (self.person_infos.count != 0) {
            if (self.dog_infos.count != 0) {
                Dog *info = self.dog_infos[indexPath.row];
                cell.textLabel.text = info.name;
            }
            else {
                cell.textLabel.text = @"这个人没养狗";
            }
        }
        
        return cell;
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.detailTableView) {
        if (self.dog_infos.count == 0) {
            return NO;
        }
    }
    
    return YES;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.personTableView) {
        Person *info = self.person_infos[indexPath.row];
        
        RLMResults *results = [Person objectsWhere:@"id == %d", info.id];
        RLMObject *rlmObj = [results objectAtIndex:0];
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        [realm deleteObject:rlmObj];
        [realm commitWriteTransaction];
        
        [self.person_infos removeObjectAtIndex:indexPath.row];
        // 从列表中删除
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
    
    else if (tableView == self.detailTableView) {
        Dog *info = self.dog_infos[indexPath.row];
        
        RLMResults *results = [Dog objectsWhere:@"id == %d", info.id];
        Dog *dog = [results objectAtIndex:0];
        
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        [realm deleteObject:dog];
        [realm commitWriteTransaction];
        
        [self.dog_infos removeObjectAtIndex:indexPath.row];
        // 从列表中删除
        if (self.dog_infos.count) {
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }
        
//        [tableView reloadData];
    }
    
    
}

#pragma mark - tableView Delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.personTableView) {
        self.person = self.person_infos[indexPath.row];
        
        NSMutableArray *temp = [NSMutableArray array];
        for (int i = 0; i < self.person.dogs.count; i++) {
            Dog *info = self.person.dogs[i];
            [temp addObject:info];
        }
        self.dog_infos = temp;
    }
    
    [self.personTableView reloadData];
    [self.detailTableView reloadData];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}



#pragma mark - Custom Action

- (void)addPush {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AddPush" bundle:nil];
    UIViewController *vc = sb.instantiateInitialViewController;
    
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)textFieldDidChange: (UITextField *)theTextField{
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"name CONTAINS %@", theTextField.text];
    RLMResults<Person *> *personResults = [Person objectsWithPredicate:pred];
    
//    NSLog(@"%@", personResults);
    
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < personResults.count; i++) {
        Person *info = personResults[i];
        [array addObject:info];
    }
    self.person_infos = array;
    
    [self.personTableView reloadData];
    [self.detailTableView reloadData];
}

@end
